using System;
using System.Runtime.CompilerServices;
using System.Collections.Generic;
using System.IO;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Net;
using System.Text;
using System.Threading;

namespace CStock
{


	public class WebYahoo : WebBundesbank
	{
	    
        #region memebers
        private string url_yahoo_chartcsvData_US;
        private string url_yahoo_DE_ListQuotes;

        private string url_excelSheet;
        private System.Windows.Forms.Timer timerSaveQuotes;

        #endregion

        /// <summary>
        /// constructor
        /// </summary>
        public WebYahoo():base()
        {

            this.url_yahoo_chartcsvData_US = "http://ichart.finance.yahoo.com:80/table.csv?s=";
            url_excelSheet = this.url_yahoo_chartcsvData_US;

            url_yahoo_DE_ListQuotes = @"http://de.finance.yahoo.com/d/quotes.csv?s=@%5E"; //GDAXI&f=sl1d1t1c1ohgv&e=.csv
            //http://uk.finance.yahoo.com/q/cp?s=^GSPC ................... S&P
            this.timerSaveQuotes = new System.Windows.Forms.Timer();
            this.timerSaveQuotes.Interval = 10000;
            
        }
        
        private void DownloadComplete_YahooSeries_1(byte[] dataDownloaded)
        {

            string strPage = dataDownloaded.ToString();
            

        }
        
        public bool GetIntradaySeriesFromYahoo(IDataItem dataItem)
        {
            return true;
            //http://logtrade.finance.vip.ukl.yahoo.com/lastTrades?output=user&i=eu&s=SI

            //Format: 
            //10/10/08;22:00;65.349998;2800;2308289
            //10/10/08;22:00;65.349998;2800;2308289
     


        }
        public bool GetPortfolio_Index(string portolfioID, string url_Overview)
        {


            this.portfolio = new Portfolio();
            portfolio.ID = portolfioID;
            //portfolio.Symbol = url_Overview;
            portfolio.URL_Overview = url_Overview;
            portfolio.Serialize();

            YahooFeedSockets.GetYahoo_ListOfGermanIndexes(portfolio, true);
            //default url 

        
            return true;


        }
        public bool GetListOfShares_Special(string portolfioID, string url_Overview, string url_Excel, int endIterator)
        {




            YahooFeedSockets.GetYahoo_ListOfStocks_DE(portfolio, true);
            //default url 

            //Thread updateThread = new Thread(new ThreadStart(GetListOfShares_Thread));
            //updateThread.Start();
            url_excelSheet = url_Excel;
            //GetListOfShares_Thread();
            return true;


        }
        public bool UpdateListOfShares(string portolfioID, string url_Overview, string url_Excel)
        {

            
            this.portfolio = new Portfolio();
            portfolio.ID = portolfioID;
            //portfolio.Symbol = url_Overview;
            portfolio.URL_excelSheet = url_Excel;
            portfolio.URL_Overview = url_Overview;
            portfolio.Serialize();

            
            url_excelSheet = url_Excel;
         
            return true;


        }
        public bool GetListOfShares(string myexchangeSymbol, string portolfioID)
        {

            
            this.portfolio = new Portfolio();
            portfolio.ID = portolfioID;
            portfolio.Symbol = myexchangeSymbol;

            YahooFeedSockets.GetYahoo_ListOfStocks_DE(portfolio, false);
          
            url_excelSheet = this.url_yahoo_DE_ListQuotes + this.portfolio.Symbol + "&f=sl1d1t1c1ohgv&e=.csv";
           return true;


        }
  
       
        public static bool Download_Portfolio_LastQuotes(IPortfolio myportf)
        {


            StringCollection strCollection = ReadPage_ToStringCollection(myportf.URL_excelSheet);
            if (strCollection == null || strCollection.Count == 0)
                return false;
            for (int i = 0; i < strCollection.Count; i++)
            {
                string strLine = strCollection[i];
                string splitCharacter = myportf.URL_excelSheet_CommaSeparator;
                string[] listData = strLine.Split(splitCharacter.ToCharArray());
                string symbol = listData[0];
                IDataItem di = myportf.DataItems.DataItemPerSymbol(symbol);
                Debug.Assert(di != null, "DataItem is not in portolfio " + symbol);
                if (di != null)
                {
                    IQuote qu = new Quote();
                    qu.CLOSEc = Convert.ToDouble(listData[1], CUtil.Conversions.CultureGerman);
                    qu.TIME_OfDay = Convert.ToDateTime(listData[2]);
                    qu.DATE = Convert.ToDateTime(listData[3]);
                    qu.Change = Convert.ToDouble(listData[4]);
                    qu.OPENc = Convert.ToDouble(listData[5]);
                    qu.HIGH = Convert.ToDouble(listData[6]);
                    qu.LOW = Convert.ToDouble(listData[7]);
                    qu.VOLUME = Convert.ToInt64(listData[8]);

                    di.DataClass.QuoteCollection.Add(qu);
                    di.DataClass.Serialize();


                }
                
               

            }
            return true;

            
        }
        
        public bool GetTimeSeriesFromYahoo_SingleShare(IDataItem mydataItem, DateTime myDateStart, bool inThread)
        {

            this.dataItem = mydataItem;
            this.dateStart = myDateStart;
            if (inThread)
            {
                Thread updateThread = new Thread(new ThreadStart(GetTimeSeriesFromYahoo_Thread));
                updateThread.Start();

            }
            else
            {
                GetTimeSeriesFromYahoo_Thread();
            }
            return true;


        }
        public void GetTimeSeriesFromYahoo_Portfolio_Thread()
        {
            for (int i = 0; i < portfolio.DataItems.Count; i++)
            {
                this.dataItem = portfolio.DataItems[i];
                DownloadSingleShare();
                
                
            }
        }
        public bool GetTimeSeriesFromYahoo_Portfolio(IPortfolio myportfolio, DateTime myDateStart)
        {

            this.portfolio = myportfolio;
            this.dateStart = myDateStart;

            Thread updateThread = new Thread(new ThreadStart(GetTimeSeriesFromYahoo_Portfolio_Thread));
            updateThread.Start();
            return true;
            


        }

        private bool InterpretYahooLine(string strLine, ListQuotes qc)
        {
            try
            {
                if (strLine != null && strLine != string.Empty)
                {
                    IQuote qu = new Quote();
                    string[] listQuotes = strLine.Split(new Char[] { ',' });

                    qu.DATE = Convert.ToDateTime(listQuotes[0], CUtil.Conversions.CultureAmerican);


                    qu.OPENc = Convert.ToDouble(listQuotes[1], CUtil.Conversions.CultureAmerican);
                    qu.HIGH = Convert.ToDouble(listQuotes[2], CUtil.Conversions.CultureAmerican);
                    qu.LOW = Convert.ToDouble(listQuotes[3], CUtil.Conversions.CultureAmerican);
                    qu.CLOSEc = Convert.ToDouble(listQuotes[4], CUtil.Conversions.CultureAmerican);
                    qu.VOLUME = Convert.ToInt64(listQuotes[5], CUtil.Conversions.CultureAmerican);

                    double myAdjust = Convert.ToDouble(listQuotes[6], CUtil.Conversions.CultureAmerican);


                    if (qu.CLOSEc != myAdjust)
                    {
                        myAdjust /= qu.CLOSEc;
                        qu.OPENc *= myAdjust;
                        qu.HIGH *= myAdjust;
                        qu.LOW *= myAdjust;
                        qu.CLOSEc *= myAdjust;
                    }

                    if (qu.OPENc != 0)
                    {
                        if (Math.Abs(qu.OPENc) > 1e-9)
                        {
                            qc.Add(qu);
                            //if (bOnly200 && qc.Count > 200)
                            if (qu.DATE < dateStart)
                            {
                                AdjustQuoteCollection(qc, dataItem);
                                //this.RaiseObjectChangedEvent(this, "Finished download:" + dataItem.ID, this.dataItem, this.dataItem);
                                return true;
                            }


                        }
                    }

                }
                return false;
            }
            catch (Exception ex)
            {
                Debug.Assert(false, "Error interpreting line " + strLine + "; Error is : " + ex.Message);
                return false;
            }

        }
        private ListQuotes ReadYahooListOfQuotes(StringCollection strCollection)
        {
            ListQuotes qc = new ListQuotes(dataItem.DataClass);
            try
            {
                
                
                for (int iLines = 1; iLines < strCollection.Count; iLines++)
                {
                    string strLine = strCollection[iLines];
                    if (InterpretYahooLine(strLine, qc))
                        return qc;


                }

                AdjustQuoteCollection(qc, dataItem);
                return qc;
            }
            catch (Exception ex)
            {
                Debug.Assert(false, "Error ReadYahooList : " + dataItem.ID + " ; " + ex.Message);
                return qc;
            }

        }
      
        public bool DownloadSingleShare()
        {
            if (!DataItem.CheckDataItemSymbol(this.dataItem))
                return false;

            this.RaiseObjectChangedEvent(this, "Download init for: " + dataItem.ID, this.dataItem, this.dataItem);
               

            ListQuotes qc = new ListQuotes(dataItem.DataClass);
            DateTime dt = DateTime.Now;

            
            this.url_excelSheet = this.url_yahoo_chartcsvData_US + dataItem.Symbol + "&a=00&b=1&c=1900&d=" + dt.Month.ToString() + "&e=" + dt.Day.ToString() + "&f=" + dt.Year.ToString() + "&g=d&ignore=.csv";
            StringCollection strCollection = ReadPage_ToStringCollection(url_excelSheet);

            if (strCollection == null || strCollection.Count == 0)
                return false;

            CheckPresenceOfQuote(strCollection[0]);

            qc = ReadYahooListOfQuotes(strCollection);
            this.RaiseObjectChangedEvent(this, "Finished download:" + dataItem.ID, this.dataItem, this.dataItem);
            return true;

        }
       
        
        private void GetTimeSeriesFromYahoo_Thread()
        {
            if (webClientBusy)
            {
                System.Threading.Thread.Sleep(50);
                GetTimeSeriesFromYahoo_Thread();
            }
            else
            {
                

               
                try
                {
                    DownloadSingleShare();

                   
                }
                catch (Exception ex)
                {
                    System.Windows.Forms.MessageBox.Show("Error occured during web download for: " + dataItem.Name + "; " + ex.Message);
                }
                return;

                
            }
        }
        public bool DownloadIntradayQuotes(IPortfolio portf)
        {


            this.RaiseObjectChangedEvent(this, "Download init for: " + portf.ID, portf, portf);
            
            DateTime dt = DateTime.Now;

            this.url_excelSheet = @"http://download.finance.yahoo.com/d/quotes.csv?s=";
            StringBuilder sb = new StringBuilder();
            
            
            for (int i = 0; i < portf.DataItems.Count; i++)
            {
                //string strSymbol = portf.DataItems[i].Symbol_Intraday;
                string strSymbol = portf.DataItems[i].Symbol;
                if (!string.IsNullOrEmpty(strSymbol))
                {
                    sb.Append(strSymbol + ",");
                   
                }
                
                
            }
            string shareList = sb.ToString();
            //remove last ","
            shareList = shareList.Remove(shareList.Length - 1, 1);
        

            url_excelSheet += shareList;

            url_excelSheet += @"&f=st5l9c6p4b1a3&e=.csv";
            //url_excelSheet = @"http://download.finance.yahoo.com/d/quotes.csv?s=XOM,PFE,PGN,FTR&f=st5l9c6p4b1a3&e=.csv";

            //+ dataItem.Symbol + "&a=00&b=1&c=1900&d=" + dt.Month.ToString() + "&e=" + dt.Day.ToString() + "&f=" + dt.Year.ToString() + "&g=d&ignore=.csv";
            StringCollection strCollection = ReadPage_ToStringCollection(url_excelSheet);

            if (strCollection == null || strCollection.Count == 0)
                return false;

            //CheckPresenceOfQuote(strCollection[0]);

            //qc = ReadYahooListOfQuotes(strCollection);
            this.RaiseObjectChangedEvent(this, "Finished download:" + portf.ID, portf, portf);
            return true;

        }
        public bool DownloadIntradayQuotes(IDataItem di)
        {
            System.IO.StreamWriter swriter = null;
            string fileName = di.DataClass.DataClassIntraday.Path + "\\" + di.DataClass.DataClassIntraday.ID + ".txt";
            swriter = new System.IO.StreamWriter(fileName, true);

            this.timerSaveQuotes.Tick += new System.EventHandler(this.timerSaveQuotes_Tick);
            
            this.dataItem = di;
            this.RaiseObjectChangedEvent(this, "Download init for: " + dataItem.ID, dataItem, dataItem);


            //ListQuotes qc = new ListQuotes(dataItem.DataClass);
            DateTime dt = DateTime.Now;

            //=OXY&f=st5l9c6p4b1a3&e=.csv
            this.url_excelSheet = @"http://download.finance.yahoo.com/d/quotes.csv?s=";
            StringBuilder sb = new StringBuilder();
            string strSymbol = this.dataItem.Symbol;
            
            //remove last ","

            url_excelSheet += strSymbol;

            url_excelSheet += @"&f=st5l9c6p4b1a3&e=.csv";

            
            
            IList<string> quotesAsList = new List<string>();
            double fCloseOld = 0f;
            StringCollection strCollection = ReadPage_ToStringCollection(url_excelSheet);
            if (strCollection == null || strCollection.Count == 0)
                return false;
            else
            {
                double fClose = ReadIntradayLine(strCollection[0]);

                if (fClose != 0f && fClose != fCloseOld)
                {
                    fCloseOld = fClose;
                    string strQuoteLine = CreateQuoteString(fClose);
                    if (!string.IsNullOrEmpty(strQuoteLine))
                    {
                        quotesAsList.Add(strQuoteLine);
                        swriter.WriteLine(strQuoteLine);
                        
                        //lq.Add(qu);
                    }
                }
            }
            swriter.Close();

            dataItem.DataClass.DataClassIntraday.Serialize();

            //CheckPresenceOfQuote(strCollection[0]);

            //qc = ReadYahooListOfQuotes(strCollection);
            this.RaiseObjectChangedEvent(this, "Finished download:" + dataItem.ID, dataItem, dataItem);
            return true;

        }
        private string CreateQuoteString(double fClose)
        {
            string strOutput = string.Empty;
            strOutput += DateTime.Now.Hour.ToString() + "." + DateTime.Now.Minute.ToString() + "." + DateTime.Now.Second.ToString() + "&" + fClose;
            return strOutput;
        }
        private double ReadIntradayLine(string line)
        {
            //IQuote qu = new Quote();
            double fClose = 0f;
            try
            {
                
                string[] listQuotes = line.Split(new Char[] { ',' });
                fClose = Convert.ToDouble(listQuotes[2], CUtil.Conversions.CultureAmerican);
                return fClose;
            }
            catch 
            {
                //do nothing
                //Debug.Assert(false, "Error ReadYahooList : " + dataItem.ID + " ; " + ex.Message);
                return fClose;
            }

        }
        private void timerSaveQuotes_Tick(object sender, System.EventArgs e)
        {
           
            
        }
	}
}